#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Tue Jul 23 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
import json
import logging
import os
import uuid
from datetime import datetime, timedelta

from company.models import VehicleCompanyTerminal
from dispatcher.zsh import const
from third_api.zsh import ZSHApi


class BaseDispatcher:
    VENDER_CODE = 'YBAD'
    FORMAT_DT = '%Y-%m-%d %H:%M:%S'
    FILE_STATUS = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'start_ids.json')
    COORDINATE = 'GCJ02'
    LIMIT = 100

    def __init__(self, *args, **kwargs):
        self.zsh_api = ZSHApi()
        self.vehicle_infos = {}
        self.load_vehicle_infos()
        self.load_start_ids()

    def load_vehicle_infos(self):
        vehicle = VehicleCompanyTerminal.objects.filter(company__name="中运汉邦")  # 根据公司name查询所有的车辆
        for v in vehicle:
            self.vehicle_infos[v.vehicle_id] = v.vehicle.license_number

    def load_start_ids(self):
        """获取字典中起始id"""
        if os.path.exists(self.FILE_STATUS):
            with open(self.FILE_STATUS) as f:
                self.current_status = json.load(f)
                self.current_status['vehiclePosition'] = datetime.strptime(self.current_status['vehiclePosition'], "%Y-%m-%d %H:%M:%S")
        else:
            print(f"{self.FILE_STATUS}文件不存在")
            self.current_status = {
                "vehicleEvent": 0,
                "vehiclePosition": self.get_time()
            }

    def get_time(self):
        """获得当前时间八小时之前的时间"""
        dt = datetime.now()
        minute = dt.minute // 5 * 5
        return datetime(year=dt.year, month=dt.month, day=dt.day, hour=dt.hour, minute=minute)

    def dump_status(self):
        '''在每次程序结束的时候进行重新写入文件的操作'''
        self.current_status['vehiclePosition'] = self.current_status['vehiclePosition'].strftime("%Y-%m-%d %H:%M:%S")
        with open(self.FILE_STATUS, 'w') as f:
            print(self.current_status)
            f.write(json.dumps(self.current_status))
        print('--- Dump current status')

    def send(self, method_name, item_list):
        if item_list:
            url = f'{const.BASE_URL}{method_name}'
            uid = str(uuid.uuid1())
            data = {
                "msgId": str(uid),
                method_name: item_list
            }

            print(f'>>> DO POST {method_name}, data_len={len(item_list)}, date={data}')
            # # dt = datetime.utcnow()
            # # const.HEADER_TEMP['Date'] = dt.strftime('%a, %d %b %Y %H:%M:%S GMT')
            # # resp = requests.post(url=url, data={method_name: json.dumps(data, ensure_ascii=False)}, headers=const.HEADER_TEMP, verify=False)
            # # if resp.json()['responseCode'] != 200:
            # #     raise ValueError(f'<<< ERROR RESP:{resp.json()}')
